//
//  AlarmStatisticsAlarmView.swift
//  SBSafetyApp
//
//  Created by Lina on 2023/6/15.
//

import Foundation
import UIKit

// 报警信号Tab
class AlarmStatisticsAlarmView: UIView, PullToRefreshPresentable {
    var header: AlarmHeaderView!
    let aTable = AlarmTableView()
    
    var deptId: Int64?
    var deptName: String?
    
    var datas : [AlarmsModal?] = []

    var pageNum: Int = 1
    var totalPage: Int64 = 0
    
    var listParam = AlarmCommonParam(pageNum: 1, pageSize: PageSize, dateType: "1")

    init(deptId: Int64?, deptName: String?) {
        super.init(frame: .zero)
        backgroundColor = .bg

        self.deptId = deptId
        self.deptName = deptName
        header = AlarmHeaderView(deptId: deptId, deptName: deptName)
        setupUI()
        setupPullToRefresh(on: aTable.tableView)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit {
        aTable.tableView.removeAllPullToRefresh()
    }
    
    func reloadAction() {
        pageNum = 1
        getList()
    }
    
    func loadAction() {
        if pageNum >= totalPage {
            return
        }
        pageNum += 1
        getList()
    }
    
    func reloadData(withParam param: AlarmCommonParam) {
        listParam = param
        // 报警类型统计
        API.getAlarmCountByType(withParam: AlarmCommonParam(tbCompanyId: "\(deptId ?? -1)")) { responseModel in
            DispatchQueue.main.async {
                let models = responseModel.models?.filter({$0?.dictValue != "5" && $0?.dictValue != "6"})
                self.header.cardsV.updateUI(withModels: models ?? [])
            }
        }
        
        // 列表
        pageNum = 1
        getList()
    }
    
    func getList() {
        listParam.pageNum = pageNum

        showToastActivity()
        /// 报警记录
        API.getAlarmList(withParam: listParam) { responseModel in
            if self.pageNum > 1 && (responseModel.models == nil || responseModel.models?.count == 0) {
                self.pageNum -= 1
                return
            }
            if self.pageNum == 1 {
                self.datas.removeAll()
            }
            self.totalPage = responseModel.totalPage
            self.datas.append(contentsOf: responseModel.models ?? [])
            DispatchQueue.main.async {
                self.hideToastActivity()
                self.aTable.datas = self.datas
            }
        }
    }
    
    
    func setupUI() {
        addSubview(header)
        header.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
        }
        
        addSubview(aTable)
        aTable.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(header.snp.bottom)
            make.bottom.equalTo(safeAreaLayoutGuide.snp.bottom)
        }
    }
}
